package com.blacktech.dbu.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 字段名称翻译工具类
 * 提供中文名自动翻译为英文名的功能
 *
 * @author Yanyunsong
 */
@Slf4j
@Component
public class FieldTranslationUtil {

    // 常用词汇翻译映射
    private static final Map<String, String> COMMON_TRANSLATIONS = new HashMap<>();

    // 字段类型相关词汇
    private static final Map<String, String> TYPE_KEYWORDS = new HashMap<>();

    // 非法字符模式
    private static final Pattern INVALID_CHAR_PATTERN = Pattern.compile("[^a-zA-Z0-9_]");

    static {
        // 初始化常用翻译映射
        initCommonTranslations();
        initTypeKeywords();
    }

    private static void initCommonTranslations() {
        // 基础信息类
        COMMON_TRANSLATIONS.put("编号", "id");
        COMMON_TRANSLATIONS.put("标识", "id");
        COMMON_TRANSLATIONS.put("主键", "id");
        COMMON_TRANSLATIONS.put("名称", "name");
        COMMON_TRANSLATIONS.put("标题", "title");
        COMMON_TRANSLATIONS.put("描述", "description");
        COMMON_TRANSLATIONS.put("说明", "description");
        COMMON_TRANSLATIONS.put("备注", "remark");
        COMMON_TRANSLATIONS.put("内容", "content");
        COMMON_TRANSLATIONS.put("详情", "detail");
        COMMON_TRANSLATIONS.put("摘要", "summary");

        // 时间类
        COMMON_TRANSLATIONS.put("创建时间", "create_time");
        COMMON_TRANSLATIONS.put("更新时间", "update_time");
        COMMON_TRANSLATIONS.put("修改时间", "modify_time");
        COMMON_TRANSLATIONS.put("删除时间", "delete_time");
        COMMON_TRANSLATIONS.put("开始时间", "start_time");
        COMMON_TRANSLATIONS.put("结束时间", "end_time");
        COMMON_TRANSLATIONS.put("时间", "time");
        COMMON_TRANSLATIONS.put("日期", "date");

        // 状态类
        COMMON_TRANSLATIONS.put("状态", "status");
        COMMON_TRANSLATIONS.put("类型", "type");
        COMMON_TRANSLATIONS.put("级别", "level");
        COMMON_TRANSLATIONS.put("等级", "grade");
        COMMON_TRANSLATIONS.put("优先级", "priority");
        COMMON_TRANSLATIONS.put("标志", "flag");
        COMMON_TRANSLATIONS.put("是否", "is_");
        COMMON_TRANSLATIONS.put("启用", "enabled");
        COMMON_TRANSLATIONS.put("禁用", "disabled");
        COMMON_TRANSLATIONS.put("激活", "active");
        COMMON_TRANSLATIONS.put("停用", "inactive");

        // 用户相关
        COMMON_TRANSLATIONS.put("用户", "user");
        COMMON_TRANSLATIONS.put("用户名", "username");
        COMMON_TRANSLATIONS.put("用户名", "user_name");
        COMMON_TRANSLATIONS.put("账号", "account");
        COMMON_TRANSLATIONS.put("密码", "password");
        COMMON_TRANSLATIONS.put("邮箱", "email");
        COMMON_TRANSLATIONS.put("电话", "phone");
        COMMON_TRANSLATIONS.put("手机", "mobile");
        COMMON_TRANSLATIONS.put("地址", "address");

        // 业务相关
        COMMON_TRANSLATIONS.put("订单", "order");
        COMMON_TRANSLATIONS.put("订单号", "order_no");
        COMMON_TRANSLATIONS.put("产品", "product");
        COMMON_TRANSLATIONS.put("商品", "product");
        COMMON_TRANSLATIONS.put("价格", "price");
        COMMON_TRANSLATIONS.put("金额", "amount");
        COMMON_TRANSLATIONS.put("数量", "quantity");
        COMMON_TRANSLATIONS.put("库存", "stock");
        COMMON_TRANSLATIONS.put("分类", "category");
        COMMON_TRANSLATIONS.put("品牌", "brand");

        // 数字和度量
        COMMON_TRANSLATIONS.put("数量", "count");
        COMMON_TRANSLATIONS.put("总数", "total");
        COMMON_TRANSLATIONS.put("页数", "page");
        COMMON_TRANSLATIONS.put("大小", "size");
        COMMON_TRANSLATIONS.put("长度", "length");
        COMMON_TRANSLATIONS.put("宽度", "width");
        COMMON_TRANSLATIONS.put("高度", "height");
        COMMON_TRANSLATIONS.put("重量", "weight");
    }

    private static void initTypeKeywords() {
        // 字段类型关键词映射
        TYPE_KEYWORDS.put("时间", "time");
        TYPE_KEYWORDS.put("日期", "date");
        TYPE_KEYWORDS.put("数字", "num");
        TYPE_KEYWORDS.put("金额", "amount");
        TYPE_KEYWORDS.put("价格", "price");
        TYPE_KEYWORDS.put("标识", "id");
        TYPE_KEYWORDS.put("代码", "code");
        TYPE_KEYWORDS.put("标志", "flag");
        TYPE_KEYWORDS.put("状态", "status");
        TYPE_KEYWORDS.put("类型", "type");
        TYPE_KEYWORDS.put("是否", "is");
        TYPE_KEYWORDS.put("开关", "is");
        TYPE_KEYWORDS.put("计数", "count");
        TYPE_KEYWORDS.put("数量", "count");
        TYPE_KEYWORDS.put("链接", "url");
        TYPE_KEYWORDS.put("地址", "url");
    }

    /**
     * 将中文字段名翻译为英文
     *
     * @param chineseName 中文名称
     * @return 英文名称
     */
    public String translateToEnglish(String chineseName) {
        if (chineseName == null || chineseName.trim().isEmpty()) {
            return "";
        }

        String trimmedName = chineseName.trim();

        // 1. 优先使用完全匹配的翻译
        if (COMMON_TRANSLATIONS.containsKey(trimmedName)) {
            return COMMON_TRANSLATIONS.get(trimmedName);
        }

        // 2. 尝试分段翻译
        String translated = translateBySegments(trimmedName);
        if (!translated.isEmpty()) {
            return translated;
        }

        // 3. 使用关键词匹配
        translated = translateByKeywords(trimmedName);
        if (!translated.isEmpty()) {
            return translated;
        }

        // 4. 生成基于拼音的名称（这里简化处理，实际可以集成拼音库）
        return generatePinyinBasedName(trimmedName);
    }

    /**
     * 分段翻译
     */
    private String translateBySegments(String chineseName) {
        StringBuilder result = new StringBuilder();

        // 按常见分隔符分割
        String[] segments = chineseName.split("[、，,\\s\\-_]+");

        for (String segment : segments) {
            if (!segment.isEmpty()) {
                String translated = COMMON_TRANSLATIONS.getOrDefault(segment, segment);
                if (result.length() > 0) {
                    result.append("_");
                }
                result.append(translated);
            }
        }

        return result.toString();
    }

    /**
     * 关键词匹配翻译
     */
    private String translateByKeywords(String chineseName) {
        StringBuilder result = new StringBuilder();
        String remaining = chineseName;

        for (Map.Entry<String, String> entry : TYPE_KEYWORDS.entrySet()) {
            if (chineseName.contains(entry.getKey())) {
                if (result.length() > 0) {
                    result.append("_");
                }
                result.append(entry.getValue());
                remaining = remaining.replace(entry.getKey(), "");
            }
        }

        // 如果还有剩余部分，尝试常用翻译
        if (!remaining.trim().isEmpty()) {
            for (Map.Entry<String, String> entry : COMMON_TRANSLATIONS.entrySet()) {
                if (remaining.contains(entry.getKey())) {
                    if (result.length() > 0) {
                        result.append("_");
                    }
                    result.append(entry.getValue());
                }
            }
        }

        return result.toString();
    }

    /**
     * 生成基于拼音的名称（简化版本）
     */
    private String generatePinyinBasedName(String chineseName) {
        // 这里简化处理，实际应用中可以集成pinyin4j等库
        // 目前先返回一个清理后的版本
        String cleaned = INVALID_CHAR_PATTERN.matcher(chineseName).replaceAll("_");
        return cleaned.toLowerCase().replaceAll("_+", "_").replaceAll("^_|_$", "");
    }

    /**
     * 验证和规范化字段名
     *
     * @param fieldName 原始字段名
     * @return 规范化后的字段名
     */
    public String normalizeFieldName(String fieldName) {
        if (fieldName == null || fieldName.trim().isEmpty()) {
            return "field";
        }

        String normalized = fieldName.trim().toLowerCase();

        // 替换非法字符
        normalized = INVALID_CHAR_PATTERN.matcher(normalized).replaceAll("_");

        // 合并多个下划线
        normalized = normalized.replaceAll("_+", "_");

        // 移除开头和结尾的下划线
        normalized = normalized.replaceAll("^_|_$", "");

        // 如果结果为空或数字开头，添加前缀
        if (normalized.isEmpty() || normalized.matches("^\\d.*")) {
            normalized = "field_" + normalized;
        }

        // 限制长度
        if (normalized.length() > 64) {
            normalized = normalized.substring(0, 64);
        }

        return normalized;
    }

    /**
     * 检查字段名是否为数据库保留字
     *
     * @param fieldName 字段名
     * @return 是否为保留字
     */
    public boolean isReservedWord(String fieldName) {
        // 常见数据库保留字列表
        String[] reservedWords = {
            "order", "group", "user", "password", "key", "value", "type", "status",
            "create", "update", "delete", "insert", "select", "from", "where", "and", "or",
            "table", "index", "view", "trigger", "procedure", "function", "database",
            "schema", "column", "constraint", "primary", "foreign", "unique", "null"
        };

        String normalized = fieldName.toLowerCase();
        for (String reserved : reservedWords) {
            if (normalized.equals(reserved)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取字段名的建议列表
     *
     * @param chineseName 中文名称
     * @return 建议的英文名称列表
     */
    public String[] getSuggestedNames(String chineseName) {
        String primary = translateToEnglish(chineseName);
        String normalized = normalizeFieldName(primary);

        if (isReservedWord(normalized)) {
            normalized = normalized + "_field";
        }

        return new String[]{
            normalized,
            normalized + "_name",
            "field_" + normalized,
            chineseName.replaceAll("[^a-zA-Z0-9]", "_").toLowerCase()
        };
    }
}